package cn.clx.basic.controller;

import cn.clx.basic.util.AjaxResult;

import cn.clx.basic.util.FastdfsUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
//上传（post）、删除(del)
public class FastDfsController {
    /**
     * 文件的上传
     * @param file
     * @return
     */
    @PostMapping              //@requestPart 接收文件上传的注解  required = true,value = "file" 必须是file文件类型
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){
        try {
            byte[] bytes = file.getBytes();
            //得到文件名  xxx.png
            String  filename = file.getOriginalFilename();
            //利用FilenameUtils 工具类得到文件扩展名
            String extension = FilenameUtils.getExtension(filename);
            //调用工具类里面的上传方法    bytes二进制数据  extension 文件后缀名
            String path = FastdfsUtil.upload(bytes, extension);
            return AjaxResult.getAjaxResult().setResultObj(path);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.getAjaxResult().setSuccess(false).setMessage("上传失败"+e.getMessage());
        }



    }



    //    /group1/M00/00/A7/rBE3kWD3hEmAObWQAACIaoIycWk311.jpg
    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "path") String  path) throws IOException {
        try {
            String pathtemp = path.substring(1);  //  group1/M00/00/A7/rBE3kWD3hEmAObWQAACIaoIycWk311.jpg
            String group = pathtemp.substring(0, pathtemp.indexOf("/")); //  group1
            String Path = pathtemp.substring(pathtemp.indexOf("/")+1);//  M00/00/A7/rBE3kWD3hEmAObWQAACIaoIycWk311.jpg
            FastdfsUtil.delete(group,Path);
            return AjaxResult.getAjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.getAjaxResult().setSuccess(false).setMessage("删除失败！"+e.getMessage());
        }
    }
}